package com.ktmall.service.impl;

import com.ktmall.mapper.CategoryItemMapper;
import com.ktmall.mapper.GoodsItemMapper;
import com.ktmall.pojo.CategoryItem;
import com.ktmall.pojo.GoodsItem;
import com.ktmall.service.CategoryItemService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品分类相关Service实现类
 */
@Service
public class CategoryItemServiceImpl implements CategoryItemService {
    @Autowired
    private CategoryItemMapper categoryItemMapper;
    @Autowired
    private GoodsItemMapper goodsItemMapper;
    @Override
    public List<CategoryItem> getOneLevelCategory() {
        return categoryItemMapper.getOneLevelCategory();
    }

    @Override
    public List<CategoryItem> getCategoryAndGoods() {
        //1.查询出所有的商品分类列表(包括一级和二级商品分类列表)
        List<CategoryItem> allCategoryList = categoryItemMapper.findAllCategoryList();
        //2.从所有的商品分类列表中过滤一级商品分类列表
        List<CategoryItem> oneLevelList = allCategoryList.stream().filter(c ->{
            //过滤条件是category_level = 1，即商品分类的级别为1
            return c.getCategoryLevel() == 1;
        }).collect(Collectors.toList());
        //3.调用map()方法遍历一级商品分类
        oneLevelList = oneLevelList.stream().map((oneLevel) -> {
            // 查询出每个一级商品分类下的二级商品分类列表
            oneLevel.setChildren(getChildrenCategory(oneLevel, allCategoryList));
            return oneLevel;
        }).collect(Collectors.toList());
        return oneLevelList;
    }

    private List<CategoryItem> getChildrenCategory(CategoryItem oneLevel, List<CategoryItem> allCategoryList) {
        //1.从所有的商品列表中过滤出当前一级商品分类下的二级商品分类列表
        List<CategoryItem> twoLevelList = allCategoryList.stream().filter((c) -> {
            //2.过滤条件是：当前分类的父id == 当前一级分类的id
            return c.getParentId() == oneLevel.getId();
        }).map((two) -> {   //3.调用map方法遍历所有的二级商品分类
            //4.根据二级商品分类id查询出此商品分类下的商品列表
            List<GoodsItem> list = goodsItemMapper.getGoodsByCategoryId(two.getId());
            two.setGoods(list);
            return two;
        }).collect(Collectors.toList());
        return twoLevelList;
    }
}
